﻿using Microsoft.Extensions.DependencyInjection;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MTP.Core.Filters
{
    class MtpTypeFilter : IMtpFilterBase
    {
        private ObjectFactory _factory;

        public Type ImplementationType { get; }
        public int Order { get; set; }


        public MtpTypeFilter(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            ImplementationType = type;
        }

        public IMtpFilterBase CreateInstance(IServiceProvider serviceProvider,object[] arguments)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }

            if (_factory == null)
            {
                Type[] array = arguments?.Select((object a) => a.GetType())?.ToArray();
                _factory = ActivatorUtilities.CreateFactory(ImplementationType, array ?? Type.EmptyTypes);
            }

            return (IMtpFilterBase)_factory(serviceProvider, arguments);
        }
    }
}
